<template>
    <div>
        <div class="header">
            <el-color-picker v-model="color1"></el-color-picker>
            <span v-for="item in bgCplor" :key="item" :style="{ background: item }" class="header-item"
                @click="changeBgColor(item)"></span>
            <div v-for="(item, index) in imageSrc" :key="index" class="header-bg" @click="changeBgImage(item)">
                <img :src="item" alt="">
            </div>
        </div>
    </div>
</template>

<script>
import pexelsJosh from '@/assets/images/pexels-josh-shin-1585909983-30951379.jpg';
import pexelsLeefin from '@/assets/images/pexels-leefinvrede-30298523.jpg';
import pexelZeke from '@/assets/images/pexels-leefinvrede-30298523.jpg';
import { componentsShapeType } from '../utills/consts'

export default {
    inject: ['konvaStage'],
    data() {
        return {
            color1: '#ffffff',
            bgCplor: ['#ffffff', '#5271ff', '#ff914d'],
            imageSrc: [pexelsJosh, pexelsLeefin, pexelZeke],
            konva: this.konvaStage
        }
    },
    methods: {
        // 修改背景颜色
        changeBgColor(item) {
            const KonvaInstance = this.konva;
            const { stage } = KonvaInstance.stage;

            // 获取节点并检查空值
            const boardNode = stage.findOne('.board');
            if (!boardNode) return;
            const bgImage = stage.findOne('#imageid'); // 根据 ID 查找
            
            if (bgImage) bgImage.destroy();

            // 修改颜色
            boardNode.setAttr('fill', item); // 直接设置新颜色
            stage.batchDraw(); // 强制重绘画布
        },
        changeBgImage(url) {
            const KonvaInstance = this.konva;
            const { stage } = KonvaInstance.stage;
            const boardAttr = stage.findOne('.board').getAttrs();
            // 查找上一次的背景图片并删除
            const bgImage = stage.findOne('#imageid'); 
            if (bgImage) bgImage.destroy();

            const image = new Image();
            image.src = url;

            image.onload = () => {
                KonvaInstance.stage.drawShapes(componentsShapeType.IMAGE, {
                    x: boardAttr.x,
                    y: boardAttr.y,
                },
                    {
                        image: image,
                        width: boardAttr.width,
                        height: boardAttr.height,
                        draggable: false,
                        name: 'bgImage',
                        id: 'imageid',
                        type: componentsShapeType.IMAGE
                    }
                )
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.header {
    display: flex;
    flex-wrap: wrap;

    .header-item {
        width: 35px;
        height: 35px;
        margin: 3px 10px 10px 10px;
        cursor: pointer;
    }

    .header-bg {
        display: flex;
        margin: 10px;

        img {
            width: 50%;
            cursor: pointer;
        }
    }
}
</style>